"""
简历管理视图
"""
from django.db import transaction
from django.shortcuts import get_object_or_404
from django.http import HttpResponse, FileResponse
from django.conf import settings
from django.utils import timezone
from django.views.decorators.csrf import csrf_exempt
from django.utils.decorators import method_decorator
import os
import mimetypes
from rest_framework import generics, status, viewsets
from rest_framework.decorators import api_view, permission_classes, action
from rest_framework.response import Response
from rest_framework.permissions import IsAuthenticated, IsAdminUser
from rest_framework.pagination import PageNumberPagination
from accounts.permissions import IsTeacherOrAdmin
from students.models import Student
from .models import (
    Resume, ResumeTemplate, BasicInfo, Education, Skill,
    Project, WorkExperience, Award, SelfIntroduction,
    ResumeReview, ResumeVersion, ResumeSubmission
)
from .serializers import (
    ResumeListSerializer, ResumeDetailSerializer, ResumeCreateSerializer,
    ResumeTemplateSerializer, BasicInfoSerializer, EducationSerializer,
    SkillSerializer, ProjectSerializer, WorkExperienceSerializer,
    AwardSerializer, SelfIntroductionSerializer, FileUploadSerializer
)
from .dify_service import dify_service, DifyAPIError
from jobs.models import Job
from django.core.files.base import ContentFile
import json
import logging

logger = logging.getLogger(__name__)


def get_student_for_user(user):
    """获取用户对应的学生对象"""
    try:
        # 首先尝试通过user字段查找
        return Student.objects.get(user=user)
    except Student.DoesNotExist:
        # 如果没有关联用户，尝试通过邮箱查找
        try:
            return Student.objects.get(email=user.email)
        except Student.DoesNotExist:
            return None


class ResumePagination(PageNumberPagination):
    """简历分页"""
    page_size = 10
    page_size_query_param = 'page_size'
    max_page_size = 50


class ResumeViewSet(viewsets.ModelViewSet):
    """简历管理ViewSet"""
    permission_classes = [IsAuthenticated]
    pagination_class = ResumePagination

    def get_queryset(self):
        """获取当前用户的简历"""
        student = get_student_for_user(self.request.user)
        if student:
            return Resume.objects.filter(student=student).order_by('-updated_at')
        return Resume.objects.none()

    def get_serializer_class(self):
        """根据动作选择序列化器"""
        if self.action == 'list':
            return ResumeListSerializer
        elif self.action == 'create':
            return ResumeCreateSerializer
        else:
            return ResumeDetailSerializer

    def perform_create(self, serializer):
        """创建简历时设置学生"""
        student = get_student_for_user(self.request.user)
        if student:
            serializer.save(student=student)
        else:
            from rest_framework import serializers
            raise serializers.ValidationError('当前用户不是学生')

    def destroy(self, request, *args, **kwargs):
        """删除简历"""
        try:
            instance = self.get_object()
            resume_title = instance.title
            self.perform_destroy(instance)
            return Response({
                'message': f'简历"{resume_title}"删除成功',
                'status': 'success'
            }, status=status.HTTP_200_OK)
        except Exception as e:
            return Response({
                'message': '删除失败',
                'error': str(e),
                'status': 'error'
            }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

    @action(detail=True, methods=['post'])
    def upload_file(self, request, pk=None):
        """上传简历文件"""
        resume = self.get_object()
        serializer = FileUploadSerializer(data=request.data)

        if serializer.is_valid():
            resume.uploaded_file = serializer.validated_data['file']
            resume.resume_type = 'uploaded'
            if serializer.validated_data.get('title'):
                resume.title = serializer.validated_data['title']

            # 上传文件后，设置完成度为100%，状态改为制作中
            resume.completion_rate = 100.0
            if resume.status == 'draft':
                resume.status = 'in_progress'

            resume.save()

            return Response({
                'message': '文件上传成功',
                'file_url': resume.uploaded_file.url if resume.uploaded_file else None,
                'completion_rate': resume.completion_rate,
                'status': resume.status
            })

        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

    @action(detail=True, methods=['get'])
    def download(self, request, pk=None):
        """下载简历文件"""
        resume = self.get_object()

        # 检查权限：管理员、老师和简历所有者可以下载
        user = request.user
        has_permission = False

        if user.role == 'admin':
            # 管理员可以下载所有简历
            has_permission = True
        elif user.role == 'teacher':
            # 老师可以下载所有学生的简历（用于审核）
            has_permission = True
        elif user.role == 'student':
            # 学生只能下载自己的简历
            student = get_student_for_user(user)
            if student and resume.student == student:
                has_permission = True

        if not has_permission:
            return Response({'error': '无权限下载此简历'}, status=status.HTTP_403_FORBIDDEN)

        file_path = None
        file_name = None
        content_type = 'application/octet-stream'

        if resume.uploaded_file:
            # 上传的文件
            file_path = resume.uploaded_file.path
            file_name = resume.uploaded_file.name.split('/')[-1]
            # 根据文件扩展名设置content type
            if file_name.lower().endswith('.pdf'):
                content_type = 'application/pdf'
            elif file_name.lower().endswith(('.doc', '.docx')):
                content_type = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
        elif resume.generated_file:
            # 旧版生成的文件
            file_path = resume.generated_file.path
            file_name = resume.generated_file.name.split('/')[-1]
            content_type = 'application/pdf'
        elif resume.generated_file_url and resume.generated_file_name:
            # 新版生成的文件
            import os
            file_path = os.path.join(settings.MEDIA_ROOT, 'resume_files', resume.generated_file_name)
            file_name = resume.generated_file_name
            if resume.generated_file_type == 'pdf':
                content_type = 'application/pdf'
            else:
                content_type = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
        else:
            return Response({'error': '没有可下载的文件'}, status=status.HTTP_404_NOT_FOUND)

        # 检查文件是否存在
        if not os.path.exists(file_path):
            return Response({'error': '文件不存在'}, status=status.HTTP_404_NOT_FOUND)

        try:
            # 返回文件内容
            with open(file_path, 'rb') as f:
                response = HttpResponse(f.read(), content_type=content_type)
                response['Content-Disposition'] = f'attachment; filename="{file_name}"'
                return response
        except Exception as e:
            return Response({'error': f'文件读取失败: {str(e)}'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

    @action(detail=True, methods=['post'])
    def update_completion(self, request, pk=None):
        """更新简历完成度"""
        resume = self.get_object()

        try:
            # 重新计算完成度
            if resume.resume_type == 'generated':
                new_rate = resume.calculate_actual_completion_rate()
            else:
                new_rate = float(resume.completion_rate) if resume.completion_rate else 0.0

            return Response({
                'message': '完成度更新成功',
                'completion_rate': new_rate,
                'resume_id': resume.id
            })
        except Exception as e:
            return Response({
                'error': f'更新完成度失败: {str(e)}'
            }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

    @action(detail=True, methods=['post'])
    def ai_evaluation(self, request, pk=None):
        """AI简历评估（异步）"""
        resume = self.get_object()

        # 检查权限：只有简历所有者可以进行AI评估
        student = get_student_for_user(request.user)
        if not student or resume.student != student:
            return Response({
                'error': '无权限对此简历进行AI评估'
            }, status=status.HTTP_403_FORBIDDEN)

        # 检查简历状态 - 只有正在进行中的评估不能重新开始
        if resume.ai_evaluation_status == 'in_progress':
            # 检查是否是卡住的任务（超过10分钟）
            from django.utils import timezone
            from datetime import timedelta

            if resume.updated_at and resume.updated_at < timezone.now() - timedelta(minutes=10):
                logger.warning(f"检测到卡住的评估任务，重置状态 - Resume ID: {resume.id}")
                resume.ai_evaluation_status = 'failed'
                resume.ai_evaluation_error = '上次评估任务超时，已重置'
                resume.save()
            else:
                return Response({
                    'error': '简历正在评估中，请稍后再试'
                }, status=status.HTTP_400_BAD_REQUEST)

        # 获取岗位信息
        job_id = request.data.get('job_id')
        if not job_id:
            return Response({
                'error': '请选择要评估的岗位'
            }, status=status.HTTP_400_BAD_REQUEST)

        try:
            job = Job.objects.get(id=job_id, status='published')
        except Job.DoesNotExist:
            return Response({
                'error': '岗位不存在或未发布'
            }, status=status.HTTP_404_NOT_FOUND)

        # 启动异步AI评估任务
        logger.info(f"启动异步AI评估任务 - Resume ID: {resume.id}, 学生: {student.name}, 岗位: {job.title}")

        # 更新评估状态为进行中
        resume.ai_evaluation_status = 'in_progress'
        resume.ai_evaluation_error = None
        resume.save()

        # 启动异步任务
        from .tasks import ai_evaluation_task
        user_id = f"student_{student.id}"

        try:
            task = ai_evaluation_task.delay(
                resume_id=resume.id,
                job_id=job.id,
                user_id=user_id
            )

            logger.info(f"异步AI评估任务已启动 - Task ID: {task.id}, Resume ID: {resume.id}")

            return Response({
                'message': '已经开始评估，稍后在通知中心查看结果',
                'task_id': task.id,
                'evaluation_status': resume.ai_evaluation_status,
                'resume_id': resume.id,
                'job_title': job.title,
                'timeout_info': '评估预计需要1-10分钟，如超过10分钟未完成将自动重置状态',
                'notification_message': '评估完成后，您将在页面右上角的通知中心收到结果通知，可直接查看或下载评估报告。'
            })

        except Exception as e:
            # 任务启动失败，恢复状态
            resume.ai_evaluation_status = 'not_started'
            resume.ai_evaluation_error = f'任务启动失败: {str(e)}'
            resume.save()

            logger.error(f"启动AI评估任务失败 - Resume ID: {resume.id}, Error: {str(e)}")

            return Response({
                'error': f'启动评估任务失败: {str(e)}'
            }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

    @action(detail=True, methods=['get'])
    def ai_evaluation_status(self, request, pk=None):
        """查询AI评估状态

        注意：不要使用self.get_object()，否则当简历存在但不属于当前用户时会返回404，
        使前端误以为资源不存在。这里先取出对象，再进行权限校验，未授权时返回403。
        """
        resume = get_object_or_404(Resume, pk=pk)

        # 检查权限：只有简历所有者可以查询AI评估状态
        student = get_student_for_user(request.user)
        if not student or resume.student != student:
            return Response({
                'error': '无权限查询此简历的评估状态'
            }, status=status.HTTP_403_FORBIDDEN)

        return Response({
            'evaluation_status': resume.ai_evaluation_status,
            'evaluation_at': resume.ai_evaluation_at,
            'evaluation_error': resume.ai_evaluation_error,
            'has_evaluation_file': bool(resume.ai_evaluation_file),
            'has_evaluation_content': bool(resume.ai_evaluation_content),
            'job_position': resume.ai_evaluation_job_position,
            'download_url': f'/api/resume-management/resumes/{resume.id}/download_ai_evaluation/' if resume.ai_evaluation_file else None
        })

    @action(detail=True, methods=['get'])
    def ai_evaluation_result(self, request, pk=None):
        """获取AI评估结果内容"""
        resume = self.get_object()

        # 检查权限：只有简历所有者可以查看AI评估结果
        student = get_student_for_user(request.user)
        if not student or resume.student != student:
            return Response({
                'error': '无权限查看此简历的评估结果'
            }, status=status.HTTP_403_FORBIDDEN)

        # 检查是否有评估结果
        if resume.ai_evaluation_status != 'completed':
            return Response({
                'error': '评估尚未完成或失败',
                'status': resume.ai_evaluation_status,
                'error_message': resume.ai_evaluation_error
            }, status=status.HTTP_400_BAD_REQUEST)

        try:
            # 优先使用数据库中的内容
            evaluation_content = resume.ai_evaluation_content

            # 如果数据库中没有内容，尝试从文件读取
            if not evaluation_content and resume.ai_evaluation_file:
                import os
                if os.path.exists(resume.ai_evaluation_file.path):
                    with open(resume.ai_evaluation_file.path, 'r', encoding='utf-8') as f:
                        evaluation_content = f.read()

            if not evaluation_content:
                return Response({
                    'error': '评估内容为空'
                }, status=status.HTTP_404_NOT_FOUND)

            return Response({
                'status': resume.ai_evaluation_status,
                'content': evaluation_content,
                'evaluation_at': resume.ai_evaluation_at,
                'job_position': resume.ai_evaluation_job_position,
                'has_file': bool(resume.ai_evaluation_file),
                'download_url': f'/api/resume-management/resumes/{resume.id}/download_ai_evaluation/' if resume.ai_evaluation_file else None
            })

        except Exception as e:
            logger.error(f"获取AI评估结果失败 - Resume ID: {resume.id}, Error: {str(e)}")
            return Response({
                'error': f'获取评估结果失败: {str(e)}'
            }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

    @action(detail=True, methods=['get'])
    def download_ai_evaluation(self, request, pk=None):
        """下载AI评估报告"""
        resume = self.get_object()

        # 检查权限：只有简历所有者可以下载AI评估报告
        student = get_student_for_user(request.user)
        if not student or resume.student != student:
            return Response({
                'error': '无权限下载此评估报告'
            }, status=status.HTTP_403_FORBIDDEN)

        # 检查是否有评估报告
        if not resume.ai_evaluation_file:
            return Response({
                'error': '暂无AI评估报告'
            }, status=status.HTTP_404_NOT_FOUND)

        # 检查文件是否存在
        if not os.path.exists(resume.ai_evaluation_file.path):
            return Response({
                'error': '评估报告文件不存在'
            }, status=status.HTTP_404_NOT_FOUND)

        try:
            # 返回文件内容
            with open(resume.ai_evaluation_file.path, 'rb') as f:
                response = HttpResponse(f.read(), content_type='text/markdown')
                file_name = f"AI评估报告_{resume.title}_{timezone.now().strftime('%Y%m%d')}.md"
                response['Content-Disposition'] = f'attachment; filename="{file_name}"'
                return response
        except Exception as e:
            return Response({
                'error': f'文件读取失败: {str(e)}'
            }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

    @action(detail=True, methods=['get'])
    def get_ai_evaluation(self, request, pk=None):
        """获取AI评估结果内容（用于前端预览）"""
        resume = self.get_object()

        # 检查权限：只有简历所有者可以查看AI评估结果
        student = get_student_for_user(request.user)
        if not student or resume.student != student:
            return Response({
                'error': '无权限查看此评估结果'
            }, status=status.HTTP_403_FORBIDDEN)

        # 检查评估状态
        if resume.ai_evaluation_status == 'not_started':
            return Response({
                'error': '尚未进行AI评估'
            }, status=status.HTTP_404_NOT_FOUND)
        elif resume.ai_evaluation_status == 'in_progress':
            return Response({
                'message': '评估正在进行中，请稍后查看',
                'status': 'in_progress'
            })
        elif resume.ai_evaluation_status == 'failed':
            return Response({
                'error': f'评估失败: {resume.ai_evaluation_error or "未知错误"}'
            }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

        # 检查是否有评估内容
        if not resume.ai_evaluation_content and not resume.ai_evaluation_file:
            return Response({
                'error': '暂无评估结果'
            }, status=status.HTTP_404_NOT_FOUND)

        try:
            # 优先使用数据库中的内容
            evaluation_content = resume.ai_evaluation_content

            # 如果数据库中没有内容，尝试从文件读取
            if not evaluation_content and resume.ai_evaluation_file:
                if os.path.exists(resume.ai_evaluation_file.path):
                    with open(resume.ai_evaluation_file.path, 'r', encoding='utf-8') as f:
                        evaluation_content = f.read()

            if not evaluation_content:
                return Response({
                    'error': '评估内容为空'
                }, status=status.HTTP_404_NOT_FOUND)

            return Response({
                'status': resume.ai_evaluation_status,
                'content': evaluation_content,
                'evaluation_at': resume.ai_evaluation_at,
                'job_position': resume.ai_evaluation_job_position,
                'has_file': bool(resume.ai_evaluation_file),
                'download_url': f'/api/resume-management/resumes/{resume.id}/download_ai_evaluation/' if resume.ai_evaluation_file else None
            })

        except Exception as e:
            logger.error(f"获取AI评估结果失败 - Resume ID: {resume.id}, Error: {str(e)}")
            return Response({
                'error': f'获取评估结果失败: {str(e)}'
            }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

    def _extract_resume_content(self, resume):
        """提取简历内容"""
        try:
            logger.info(f"开始提取简历内容 - Resume ID: {resume.id}, 类型: {resume.resume_type}")
            content_parts = []

            # 对于上传简历，尝试解析上传的文件内容
            if resume.resume_type == 'uploaded' and resume.uploaded_file:
                try:
                    logger.info(f"尝试解析上传文件: {resume.uploaded_file}")
                    file_content = self._extract_file_content(resume.uploaded_file.path)
                    if file_content and file_content.strip():
                        logger.info(f"成功解析上传文件，内容长度: {len(file_content)}")
                        return file_content
                except Exception as e:
                    logger.warning(f"解析上传文件失败: {e}，将使用结构化数据")

            # 基本信息
            try:
                basic_info = resume.basicinfo
                content_parts.append(f"""
## 基本信息
姓名：{basic_info.name or ''}
性别：{basic_info.gender or ''}
电话：{basic_info.phone or ''}
邮箱：{basic_info.email or ''}
地址：{basic_info.address or ''}
求职意向：{basic_info.job_intention or ''}
期望薪资：{basic_info.expected_salary or ''}
工作地点：{basic_info.work_location or ''}
""")
                logger.info("成功提取基本信息")
            except BasicInfo.DoesNotExist:
                logger.warning("简历没有基本信息")
                pass

            # 教育经历
            education_list = resume.education_set.all()
            if education_list:
                content_parts.append("\n## 教育经历")
                for edu in education_list:
                    content_parts.append(f"""
学校：{edu.school_name}
专业：{edu.major}
学历：{edu.degree}
时间：{edu.start_date} - {edu.end_date or '至今'}
GPA：{edu.gpa or ''}
描述：{edu.description or ''}
""")
                logger.info(f"成功提取教育经历: {education_list.count()}条")

            # 技能特长
            skill_list = resume.skill_set.all()
            if skill_list:
                content_parts.append("\n## 技能特长")
                for skill in skill_list:
                    content_parts.append(f"""
技能名称：{skill.name}
熟练程度：{skill.level}
描述：{skill.description or ''}
""")

            # 项目经历
            project_list = resume.project_set.all()
            if project_list:
                content_parts.append("\n## 项目经历")
                for project in project_list:
                    content_parts.append(f"""
项目名称：{project.name}
角色：{project.role}
时间：{project.start_date} - {project.end_date or '至今'}
项目概况：{project.overview or ''}
承担任务：{project.responsibilities or ''}
所属组织：{project.company_or_organization or ''}
问题和总结：{project.problems_and_summary or ''}
使用技术：{project.technologies or ''}
项目成果：{project.achievements or ''}
""")
                logger.info(f"成功提取项目经历: {project_list.count()}条")

            # 工作经历
            work_list = resume.workexperience_set.all()
            if work_list:
                content_parts.append("\n## 工作经历")
                for work in work_list:
                    content_parts.append(f"""
公司：{work.company_name}
职位：{work.position_name or work.position or ''}
时间：{work.start_date} - {work.end_date or '至今'}
岗位职责：{work.job_responsibilities or ''}
工作描述：{work.description or ''}
工作成果：{work.achievements or ''}
""")
                logger.info(f"成功提取工作经历: {work_list.count()}条")

            # 获奖情况
            award_list = resume.award_set.all()
            if award_list:
                content_parts.append("\n## 获奖情况")
                for award in award_list:
                    content_parts.append(f"""
奖项名称：{award.award_name or award.name or ''}
获奖时间：{award.date_received}
奖项等级：{award.award_level or ''}
颁发机构：{award.issuer or ''}
奖项描述：{award.award_description or award.description or ''}
""")
                logger.info(f"成功提取获奖情况: {award_list.count()}条")

            # 自我介绍
            if hasattr(resume, 'selfintroduction') and resume.selfintroduction:
                intro = resume.selfintroduction
                content_parts.append(f"""
## 自我介绍
{intro.content or ''}
""")

            final_content = '\n'.join(content_parts)
            logger.info(f"简历内容提取完成 - Resume ID: {resume.id}, 内容长度: {len(final_content)}")

            # 如果内容为空或太短，记录详细信息
            if len(final_content.strip()) < 50:
                logger.warning(f"简历内容过短 - Resume ID: {resume.id}, 内容: {final_content[:200]}")

            return final_content

        except Exception as e:
            logger.error(f"提取简历内容失败 - Resume ID: {resume.id}, Error: {str(e)}")
            import traceback
            logger.error(f"详细错误信息: {traceback.format_exc()}")
            return ""

    def _extract_file_content(self, file_path):
        """从文件中提取文本内容"""
        import os
        import mimetypes

        if not os.path.exists(file_path):
            logger.error(f"文件不存在: {file_path}")
            return None

        # 获取文件扩展名
        file_ext = os.path.splitext(file_path)[1].lower()
        logger.info(f"解析文件: {file_path}, 扩展名: {file_ext}")

        try:
            # PDF文档解析
            if file_ext == '.pdf':
                return self._extract_from_pdf(file_path)

            # Word文档解析
            elif file_ext in ['.docx', '.doc']:
                return self._extract_from_word(file_path)

            # 文本文件
            elif file_ext in ['.txt', '.md']:
                return self._extract_from_text(file_path)

            else:
                logger.warning(f"不支持的文件格式: {file_ext}")
                return None

        except Exception as e:
            logger.error(f"文件解析失败: {file_path}, 错误: {str(e)}")
            return None

    def _extract_from_pdf(self, file_path):
        """从PDF文档中提取文本"""
        try:
            import PyPDF2

            logger.info(f"使用PyPDF2解析PDF文档: {file_path}")

            with open(file_path, 'rb') as file:
                pdf_reader = PyPDF2.PdfReader(file)

                # 提取所有页面的文本
                text_content = []
                for page_num in range(len(pdf_reader.pages)):
                    page = pdf_reader.pages[page_num]
                    page_text = page.extract_text()
                    if page_text.strip():
                        text_content.append(page_text.strip())

                content = '\n'.join(text_content)
                logger.info(f"PDF文档解析成功，提取文本长度: {len(content)}")

                return content if content.strip() else None

        except ImportError:
            logger.error("PyPDF2库未安装，无法解析PDF文档")
            return None
        except Exception as e:
            logger.error(f"PDF文档解析失败: {str(e)}")
            return None

    def _extract_from_word(self, file_path):
        """从Word文档中提取文本"""
        try:
            from docx import Document

            logger.info(f"使用python-docx解析Word文档: {file_path}")

            # 读取Word文档
            doc = Document(file_path)

            # 提取所有段落的文本
            paragraphs = []
            for paragraph in doc.paragraphs:
                text = paragraph.text.strip()
                if text:  # 只添加非空段落
                    paragraphs.append(text)

            # 提取表格中的文本
            for table in doc.tables:
                for row in table.rows:
                    row_text = []
                    for cell in row.cells:
                        cell_text = cell.text.strip()
                        if cell_text:
                            row_text.append(cell_text)
                    if row_text:
                        paragraphs.append(' | '.join(row_text))

            content = '\n'.join(paragraphs)
            logger.info(f"Word文档解析成功，提取文本长度: {len(content)}")

            return content if content.strip() else None

        except ImportError:
            logger.error("python-docx库未安装，无法解析Word文档")
            return None
        except Exception as e:
            logger.error(f"Word文档解析失败: {str(e)}")
            return None

    def _extract_from_text(self, file_path):
        """从文本文件中提取内容"""
        try:
            logger.info(f"读取文本文件: {file_path}")

            # 尝试不同的编码
            encodings = ['utf-8', 'gbk', 'gb2312', 'latin-1']

            for encoding in encodings:
                try:
                    with open(file_path, 'r', encoding=encoding) as file:
                        content = file.read()
                        if content.strip():
                            logger.info(f"文本文件读取成功，编码: {encoding}, 长度: {len(content)}")
                            return content
                except UnicodeDecodeError:
                    continue

            logger.error("无法使用任何编码读取文本文件")
            return None

        except Exception as e:
            logger.error(f"文本文件读取失败: {str(e)}")
            return None


class ResumeTemplateViewSet(viewsets.ModelViewSet):
    """简历模板ViewSet"""
    serializer_class = ResumeTemplateSerializer
    permission_classes = [IsAuthenticated]

    def get_queryset(self):
        """根据用户角色返回不同的查询集"""
        if self.request.user.role in ['admin', 'teacher']:
            # 管理员和老师可以看到所有模板
            return ResumeTemplate.objects.all().order_by('-created_at')
        else:
            # 学生只能看到启用的模板
            return ResumeTemplate.objects.filter(is_active=True).order_by('name')

    def get_permissions(self):
        """根据操作类型设置权限"""
        if self.action in ['create', 'update', 'partial_update', 'destroy']:
            # 创建、更新、删除操作需要管理员权限
            permission_classes = [IsTeacherOrAdmin]
        else:
            # 查看操作只需要登录
            permission_classes = [IsAuthenticated]

        return [permission() for permission in permission_classes]


# 简历各部分的ViewSet
class BasicInfoViewSet(viewsets.ModelViewSet):
    """基本信息ViewSet"""
    serializer_class = BasicInfoSerializer
    permission_classes = [IsAuthenticated]

    def get_queryset(self):
        resume_id = self.kwargs.get('resume_pk')
        student = get_student_for_user(self.request.user)
        if student:
            return BasicInfo.objects.filter(resume_id=resume_id, resume__student=student)
        return BasicInfo.objects.none()

    def perform_create(self, serializer):
        resume_id = self.kwargs.get('resume_pk')
        serializer.save(resume_id=resume_id)


class EducationViewSet(viewsets.ModelViewSet):
    """教育背景ViewSet"""
    serializer_class = EducationSerializer
    permission_classes = [IsAuthenticated]

    def get_queryset(self):
        resume_id = self.kwargs.get('resume_pk')
        student = get_student_for_user(self.request.user)
        if student:
            return Education.objects.filter(resume_id=resume_id, resume__student=student)
        return Education.objects.none()

    def perform_create(self, serializer):
        resume_id = self.kwargs.get('resume_pk')
        serializer.save(resume_id=resume_id)


class SkillViewSet(viewsets.ModelViewSet):
    """技能ViewSet"""
    serializer_class = SkillSerializer
    permission_classes = [IsAuthenticated]

    def get_queryset(self):
        resume_id = self.kwargs.get('resume_pk')
        student = get_student_for_user(self.request.user)
        if student:
            return Skill.objects.filter(resume_id=resume_id, resume__student=student)
        return Skill.objects.none()

    def perform_create(self, serializer):
        resume_id = self.kwargs.get('resume_pk')
        serializer.save(resume_id=resume_id)


class ProjectViewSet(viewsets.ModelViewSet):
    """项目经验ViewSet"""
    serializer_class = ProjectSerializer
    permission_classes = [IsAuthenticated]

    def get_queryset(self):
        resume_id = self.kwargs.get('resume_pk')
        student = get_student_for_user(self.request.user)
        if student:
            return Project.objects.filter(resume_id=resume_id, resume__student=student)
        return Project.objects.none()

    def perform_create(self, serializer):
        resume_id = self.kwargs.get('resume_pk')
        serializer.save(resume_id=resume_id)


class WorkExperienceViewSet(viewsets.ModelViewSet):
    """工作经验ViewSet"""
    serializer_class = WorkExperienceSerializer
    permission_classes = [IsAuthenticated]

    def get_queryset(self):
        resume_id = self.kwargs.get('resume_pk')
        student = get_student_for_user(self.request.user)
        if student:
            return WorkExperience.objects.filter(resume_id=resume_id, resume__student=student)
        return WorkExperience.objects.none()

    def perform_create(self, serializer):
        resume_id = self.kwargs.get('resume_pk')
        serializer.save(resume_id=resume_id)


class AwardViewSet(viewsets.ModelViewSet):
    """获奖证书ViewSet"""
    serializer_class = AwardSerializer
    permission_classes = [IsAuthenticated]

    def get_queryset(self):
        resume_id = self.kwargs.get('resume_pk')
        student = get_student_for_user(self.request.user)
        if student:
            return Award.objects.filter(resume_id=resume_id, resume__student=student)
        return Award.objects.none()

    def perform_create(self, serializer):
        resume_id = self.kwargs.get('resume_pk')
        serializer.save(resume_id=resume_id)


class SelfIntroductionViewSet(viewsets.ModelViewSet):
    """自我介绍ViewSet"""
    serializer_class = SelfIntroductionSerializer
    permission_classes = [IsAuthenticated]

    def get_queryset(self):
        resume_id = self.kwargs.get('resume_pk')
        student = get_student_for_user(self.request.user)
        if student:
            return SelfIntroduction.objects.filter(resume_id=resume_id, resume__student=student)
        return SelfIntroduction.objects.none()

    def perform_create(self, serializer):
        resume_id = self.kwargs.get('resume_pk')

        # 检查是否已存在自我介绍记录
        existing = SelfIntroduction.objects.filter(resume_id=resume_id).first()
        if existing:
            # 如果已存在，更新现有记录而不是创建新记录
            for attr, value in serializer.validated_data.items():
                setattr(existing, attr, value)
            existing.save()
            # 返回更新后的实例
            serializer.instance = existing
        else:
            # 如果不存在，创建新记录
            serializer.save(resume_id=resume_id)

    def create(self, request, *args, **kwargs):
        """重写create方法以处理一对一关系"""
        resume_id = self.kwargs.get('resume_pk')

        # 检查是否已存在记录
        existing = SelfIntroduction.objects.filter(resume_id=resume_id).first()
        if existing:
            # 如果已存在，使用update逻辑
            serializer = self.get_serializer(existing, data=request.data, partial=True)
            serializer.is_valid(raise_exception=True)
            serializer.save()
            return Response(serializer.data, status=status.HTTP_200_OK)
        else:
            # 如果不存在，使用正常的create逻辑
            return super().create(request, *args, **kwargs)

    def list(self, request, *args, **kwargs):
        """重写list方法，如果存在记录则返回单个对象而不是列表"""
        resume_id = self.kwargs.get('resume_pk')
        student = get_student_for_user(self.request.user)

        if student:
            self_intro = SelfIntroduction.objects.filter(
                resume_id=resume_id,
                resume__student=student
            ).first()

            if self_intro:
                serializer = self.get_serializer(self_intro)
                return Response(serializer.data, status=status.HTTP_200_OK)

        # 如果没有找到记录，返回空列表
        return Response([], status=status.HTTP_200_OK)


# 保留一些原有的API函数
@api_view(['POST'])
@permission_classes([IsAuthenticated])
def generate_resume(request, pk):
    """生成简历"""
    try:
        from django.http import HttpResponse
        from .resume_generator import ResumeGenerator

        student = get_student_for_user(request.user)
        if not student:
            return Response({'error': '当前用户不是学生'}, status=status.HTTP_403_FORBIDDEN)

        resume = get_object_or_404(Resume, pk=pk, student=student)

        # 获取生成格式，默认为docx
        format_type = request.data.get('format', 'docx')

        # 收集简历数据
        resume_data = {
            'title': resume.title,
            'basic_info': None,
            'self_introduction': None,
            'education': [],
            'skills': [],
            'projects': [],
            'work_experience': [],
            'awards': []
        }

        # 获取基本信息
        try:
            basic_info = BasicInfo.objects.get(resume=resume)
            resume_data['basic_info'] = {
                'name': basic_info.name,
                'gender': basic_info.gender,
                'birth_date': str(basic_info.birth_date) if basic_info.birth_date else '',
                'phone': basic_info.phone,
                'email': basic_info.email,
                'address': basic_info.address,
                'job_intention': basic_info.job_intention,
                'expected_salary': basic_info.expected_salary,
                'work_location': basic_info.work_location,
                'avatar': basic_info.avatar.url if basic_info.avatar else None
            }
        except BasicInfo.DoesNotExist:
            pass

        # 获取自我介绍
        try:
            self_intro = SelfIntroduction.objects.get(resume=resume)
            resume_data['self_introduction'] = {
                'content': self_intro.content
            }
        except SelfIntroduction.DoesNotExist:
            pass

        # 获取教育背景
        education_list = Education.objects.filter(resume=resume).order_by('order', '-start_date')
        resume_data['education'] = [
            {
                'school_name': edu.school_name,
                'major': edu.major,
                'degree': edu.degree,
                'start_date': str(edu.start_date) if edu.start_date else '',
                'end_date': str(edu.end_date) if edu.end_date else '',
                'is_current': edu.is_current,
                'gpa': edu.gpa,
                'description': edu.description
            }
            for edu in education_list
        ]

        # 获取专业技能
        skills_list = Skill.objects.filter(resume=resume).order_by('order')
        resume_data['skills'] = [
            {
                'name': skill.name,
                'level': skill.level,
                'description': skill.description
            }
            for skill in skills_list
        ]

        # 获取项目经验
        projects_list = Project.objects.filter(resume=resume).order_by('order', '-start_date')
        resume_data['projects'] = [
            {
                'name': project.name,
                'start_date': str(project.start_date) if project.start_date else '',
                'end_date': str(project.end_date) if project.end_date else '',
                'is_current': project.is_current,
                'company_or_organization': project.company_or_organization,
                'overview': project.overview,
                'role': project.role,
                'responsibilities': project.responsibilities,
                'problems_and_summary': project.problems_and_summary,
                'technologies': project.technologies,
                'achievements': project.achievements
            }
            for project in projects_list
        ]

        # 获取工作经验
        work_list = WorkExperience.objects.filter(resume=resume).order_by('order', '-start_date')
        resume_data['work_experience'] = [
            {
                'company_name': work.company_name,
                'position_name': work.position_name,
                'start_date': str(work.start_date) if work.start_date else '',
                'end_date': str(work.end_date) if work.end_date else '',
                'is_current': work.is_current,
                'job_responsibilities': work.job_responsibilities,
                'achievements': work.achievements
            }
            for work in work_list
        ]

        # 获取获奖经历
        awards_list = Award.objects.filter(resume=resume).order_by('order', '-date_received')
        resume_data['awards'] = [
            {
                'award_name': award.award_name,
                'award_level': award.award_level,
                'date_received': str(award.date_received) if award.date_received else '',
                'award_description': award.award_description
            }
            for award in awards_list
        ]

        # 生成简历
        generator = ResumeGenerator(resume_data)

        if format_type == 'pdf':
            file_stream = generator.generate_pdf()
            file_extension = 'pdf'
            content_type = 'application/pdf'
        else:  # 默认为docx
            file_stream = generator.generate_word()
            file_extension = 'docx'
            content_type = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'

        # 生成文件名
        import uuid
        from datetime import datetime
        timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
        unique_filename = f"{resume.title}_{timestamp}_{uuid.uuid4().hex[:8]}.{file_extension}"

        # 保存文件到服务器
        import os
        from django.conf import settings

        # 确保目录存在
        resume_files_dir = os.path.join(settings.MEDIA_ROOT, 'resume_files')
        os.makedirs(resume_files_dir, exist_ok=True)

        file_path = os.path.join(resume_files_dir, unique_filename)

        # 保存文件
        with open(file_path, 'wb') as f:
            f.write(file_stream.getvalue())

        # 生成文件URL
        file_url = f"{settings.MEDIA_URL}resume_files/{unique_filename}"

        # 更新简历状态和文件信息
        # 如果是第一次生成，状态从draft变为in_progress
        # 如果已经是in_progress或其他状态，保持不变
        if resume.status == 'draft':
            resume.status = 'in_progress'

        resume.generated_file_url = file_url
        resume.generated_file_name = unique_filename
        resume.generated_file_type = format_type
        resume.generated_at = datetime.now()
        resume.save()

        # 返回生成结果
        return Response({
            'message': '简历生成成功',
            'file_url': file_url,
            'file_name': unique_filename,
            'file_type': format_type,
            'download_url': f"/api/resume-management/resumes/{pk}/download-generated/"
        }, status=status.HTTP_200_OK)

    except Exception as e:
        import traceback
        print(f"生成简历错误: {str(e)}")
        print(traceback.format_exc())
        return Response({'error': f'生成简历失败: {str(e)}'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


@api_view(['GET'])
@permission_classes([IsAuthenticated])
def download_generated_resume(request, pk):
    """下载生成的简历文件"""
    try:
        student = get_student_for_user(request.user)
        if not student:
            return Response({'error': '当前用户不是学生'}, status=status.HTTP_403_FORBIDDEN)

        resume = get_object_or_404(Resume, pk=pk, student=student)

        if not resume.generated_file_url or not resume.generated_file_name:
            return Response({'error': '简历文件不存在'}, status=status.HTTP_404_NOT_FOUND)

        # 检查文件是否存在
        import os
        from django.conf import settings

        file_path = os.path.join(settings.MEDIA_ROOT, 'resume_files', resume.generated_file_name)

        if not os.path.exists(file_path):
            return Response({'error': '文件不存在'}, status=status.HTTP_404_NOT_FOUND)

        # 设置正确的content type
        if resume.generated_file_type == 'pdf':
            content_type = 'application/pdf'
        else:
            content_type = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'

        # 返回文件
        with open(file_path, 'rb') as f:
            response = HttpResponse(f.read(), content_type=content_type)
            response['Content-Disposition'] = f'attachment; filename="{resume.generated_file_name}"'
            return response

    except Exception as e:
        import traceback
        print(f"下载简历文件错误: {str(e)}")
        print(traceback.format_exc())
        return Response({'error': f'下载失败: {str(e)}'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)








class ResumeSectionDetailView(generics.RetrieveUpdateDestroyAPIView):
    """简历章节详情"""
    permission_classes = [IsAuthenticated]

    def get(self, request, pk):
        return Response({'message': f'简历章节详情接口开发中 - ID: {pk}'})


class BasicInfoDetailView(generics.RetrieveUpdateAPIView):
    """基本信息详情"""
    permission_classes = [IsAuthenticated]

    def get(self, request, resume_id):
        return Response({'message': f'基本信息接口开发中 - Resume ID: {resume_id}'})


@api_view(['GET'])
@permission_classes([IsAuthenticated])
def serve_resume_file(request, resume_id):
    """
    代理服务简历文件，解决CORS问题
    """
    try:
        # 获取学生信息
        student = get_student_for_user(request.user)
        if not student:
            return Response({'error': '当前用户不是学生'}, status=status.HTTP_403_FORBIDDEN)

        # 获取简历
        resume = get_object_or_404(Resume, pk=resume_id, student=student)

        file_path = None
        content_type = 'application/octet-stream'

        # 确定文件路径
        if resume.uploaded_file:
            file_path = resume.uploaded_file.path
            # 根据文件扩展名确定content type
            content_type, _ = mimetypes.guess_type(file_path)
            if not content_type:
                if file_path.lower().endswith('.pdf'):
                    content_type = 'application/pdf'
                elif file_path.lower().endswith(('.doc', '.docx')):
                    content_type = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
        elif resume.generated_file:
            file_path = resume.generated_file.path
            content_type = 'application/pdf'
        elif resume.generated_file_url and resume.generated_file_name:
            file_path = os.path.join(settings.MEDIA_ROOT, 'resume_files', resume.generated_file_name)
            if resume.generated_file_type == 'pdf':
                content_type = 'application/pdf'
            else:
                content_type = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
        else:
            return Response({'error': '没有可访问的文件'}, status=status.HTTP_404_NOT_FOUND)

        # 检查文件是否存在
        if not os.path.exists(file_path):
            return Response({'error': '文件不存在'}, status=status.HTTP_404_NOT_FOUND)

        # 创建文件响应
        response = FileResponse(
            open(file_path, 'rb'),
            content_type=content_type
        )

        # 添加CORS头
        response['Access-Control-Allow-Origin'] = request.META.get('HTTP_ORIGIN', '*')
        response['Access-Control-Allow-Methods'] = 'GET, OPTIONS'
        response['Access-Control-Allow-Headers'] = 'Authorization, Content-Type, Range'
        response['Access-Control-Allow-Credentials'] = 'true'

        # 支持范围请求（用于大文件）
        if 'HTTP_RANGE' in request.META:
            response['Accept-Ranges'] = 'bytes'

        return response

    except Exception as e:
        import traceback
        print(f"服务文件错误: {str(e)}")
        print(traceback.format_exc())
        return Response({'error': f'文件服务失败: {str(e)}'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


@api_view(['GET'])
@permission_classes([IsAuthenticated])
def get_resume_file_info(request, resume_id):
    """
    获取简历文件信息，用于预览
    """
    try:
        user = request.user
        resume = get_object_or_404(Resume, id=resume_id)

        # 检查权限
        has_permission = False

        if user.role == 'admin':
            # 管理员可以查看所有简历
            has_permission = True
        elif user.role == 'teacher':
            # 老师可以查看所有学生的简历（用于审核）
            has_permission = True
        elif user.role == 'student':
            # 学生只能查看自己的简历
            student = get_student_for_user(user)
            if student and resume.student == student:
                has_permission = True

        if not has_permission:
            return Response({'error': '无权限访问此简历'}, status=status.HTTP_403_FORBIDDEN)

        file_info = {}

        if resume.resume_type == 'uploaded' and resume.uploaded_file:
            file_info = {
                'file_url': resume.uploaded_file.url,
                'file_name': resume.uploaded_file.name.split('/')[-1],
                'file_type': resume.uploaded_file.name.split('.')[-1].lower() if '.' in resume.uploaded_file.name else '',
                'file_size': resume.uploaded_file.size if hasattr(resume.uploaded_file, 'size') else 0
            }
        elif resume.resume_type == 'generated':
            if resume.generated_file_url and resume.generated_file_name:
                file_info = {
                    'file_url': resume.generated_file_url,
                    'file_name': resume.generated_file_name,
                    'file_type': resume.generated_file_type or 'docx',
                    'file_size': 0  # 生成的文件大小暂时不计算
                }
            else:
                # 如果没有生成文件，返回代理URL
                file_info = {
                    'file_url': f'/api/resume-management/resumes/{resume_id}/file/',
                    'file_name': f'{resume.title}.docx',
                    'file_type': 'docx',
                    'file_size': 0
                }
        else:
            return Response({'error': '简历文件不存在'}, status=status.HTTP_404_NOT_FOUND)

        return Response({
            'resume_id': resume.id,
            'resume_title': resume.title,
            'resume_type': resume.resume_type,
            'status': resume.status,
            'completion_rate': float(resume.completion_rate),
            **file_info
        })

    except Exception as e:
        return Response({'error': str(e)}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


@csrf_exempt
def serve_resume_file_simple(request, resume_id):
    """
    简化的简历文件服务，支持CORS和token认证
    """
    # 处理CORS预检请求
    if request.method == 'OPTIONS':
        response = HttpResponse()
        response['Access-Control-Allow-Origin'] = '*'
        response['Access-Control-Allow-Methods'] = 'GET, OPTIONS'
        response['Access-Control-Allow-Headers'] = 'Authorization, Content-Type, Range'
        response['Access-Control-Allow-Credentials'] = 'true'
        response['Access-Control-Max-Age'] = '86400'
        return response

    # 只处理GET请求
    if request.method != 'GET':
        return HttpResponse('Method not allowed', status=405)

    try:
        # 从token参数或Authorization头获取认证信息
        token = request.GET.get('token')
        if not token:
            auth_header = request.META.get('HTTP_AUTHORIZATION', '')
            if auth_header.startswith('Bearer '):
                token = auth_header[7:]

        if not token:
            return JsonResponse({'error': '未提供认证token'}, status=401)

        # 验证token并获取用户
        from rest_framework_simplejwt.tokens import AccessToken
        from django.contrib.auth import get_user_model

        try:
            access_token = AccessToken(token)
            user_id = access_token['user_id']
            User = get_user_model()
            user = User.objects.get(id=user_id)
        except Exception as e:
            return JsonResponse({'error': '无效的认证token'}, status=401)

        # 获取简历对象
        from .models import Resume
        try:
            resume = Resume.objects.get(id=resume_id)
        except Resume.DoesNotExist:
            return JsonResponse({'error': '简历不存在'}, status=404)

        # 权限检查 - 允许管理员、老师和简历所有者访问
        has_permission = False

        if user.role == 'admin':
            # 管理员可以访问所有简历
            has_permission = True
        elif user.role == 'teacher':
            # 老师只能访问分配给自己的学生的已提交审核的简历
            if (resume.student.advisor == user and
                resume.status in ['pending_review', 'under_review', 'approved', 'rejected', 'needs_revision']):
                has_permission = True
        elif user.role == 'student':
            # 学生只能访问自己的简历
            student = get_student_for_user(user)
            if student and resume.student == student:
                has_permission = True

        if not has_permission:
            return JsonResponse({'error': '无权限访问此简历'}, status=403)

        # 确定文件路径
        file_path = None
        content_type = 'application/octet-stream'

        if resume.uploaded_file:
            file_path = resume.uploaded_file.path
            if file_path.lower().endswith('.pdf'):
                content_type = 'application/pdf'
            elif file_path.lower().endswith(('.doc', '.docx')):
                content_type = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
        elif resume.generated_file:
            file_path = resume.generated_file.path
            content_type = 'application/pdf'
        elif resume.generated_file_url and resume.generated_file_name:
            file_path = os.path.join(settings.MEDIA_ROOT, 'resume_files', resume.generated_file_name)
            if resume.generated_file_type == 'pdf':
                content_type = 'application/pdf'
            else:
                content_type = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'

        if not file_path or not os.path.exists(file_path):
            response = HttpResponse('File not found', status=404)
            response['Access-Control-Allow-Origin'] = '*'
            return response

        # 返回文件
        response = FileResponse(
            open(file_path, 'rb'),
            content_type=content_type
        )
        response['Access-Control-Allow-Origin'] = '*'
        response['Access-Control-Allow-Credentials'] = 'true'

        return response

    except Exception as e:
        import traceback
        print(f"文件服务错误: {str(e)}")
        print(traceback.format_exc())
        response = HttpResponse(f'Server error: {str(e)}', status=500)
        response['Access-Control-Allow-Origin'] = '*'
        return response


class EducationListCreateView(generics.ListCreateAPIView):
    """教育背景列表和创建"""
    permission_classes = [IsAuthenticated]
    
    def get(self, request, resume_id):
        return Response({'message': f'教育背景列表接口开发中 - Resume ID: {resume_id}'})


class EducationDetailView(generics.RetrieveUpdateDestroyAPIView):
    """教育背景详情"""
    permission_classes = [IsAuthenticated]
    
    def get(self, request, pk):
        return Response({'message': f'教育背景详情接口开发中 - ID: {pk}'})


class SkillListCreateView(generics.ListCreateAPIView):
    """技能列表和创建"""
    permission_classes = [IsAuthenticated]
    
    def get(self, request, resume_id):
        return Response({'message': f'技能列表接口开发中 - Resume ID: {resume_id}'})


class SkillDetailView(generics.RetrieveUpdateDestroyAPIView):
    """技能详情"""
    permission_classes = [IsAuthenticated]
    
    def get(self, request, pk):
        return Response({'message': f'技能详情接口开发中 - ID: {pk}'})


class ProjectListCreateView(generics.ListCreateAPIView):
    """项目经验列表和创建"""
    permission_classes = [IsAuthenticated]
    
    def get(self, request, resume_id):
        return Response({'message': f'项目经验列表接口开发中 - Resume ID: {resume_id}'})


class ProjectDetailView(generics.RetrieveUpdateDestroyAPIView):
    """项目经验详情"""
    permission_classes = [IsAuthenticated]
    
    def get(self, request, pk):
        return Response({'message': f'项目经验详情接口开发中 - ID: {pk}'})


class WorkExperienceListCreateView(generics.ListCreateAPIView):
    """工作经验列表和创建"""
    permission_classes = [IsAuthenticated]
    
    def get(self, request, resume_id):
        return Response({'message': f'工作经验列表接口开发中 - Resume ID: {resume_id}'})


class WorkExperienceDetailView(generics.RetrieveUpdateDestroyAPIView):
    """工作经验详情"""
    permission_classes = [IsAuthenticated]
    
    def get(self, request, pk):
        return Response({'message': f'工作经验详情接口开发中 - ID: {pk}'})


class AwardListCreateView(generics.ListCreateAPIView):
    """获奖证书列表和创建"""
    permission_classes = [IsAuthenticated]
    
    def get(self, request, resume_id):
        return Response({'message': f'获奖证书列表接口开发中 - Resume ID: {resume_id}'})


class AwardDetailView(generics.RetrieveUpdateDestroyAPIView):
    """获奖证书详情"""
    permission_classes = [IsAuthenticated]
    
    def get(self, request, pk):
        return Response({'message': f'获奖证书详情接口开发中 - ID: {pk}'})


class SelfIntroductionDetailView(generics.RetrieveUpdateAPIView):
    """自我介绍详情"""
    permission_classes = [IsAuthenticated]
    
    def get(self, request, resume_id):
        return Response({'message': f'自我介绍接口开发中 - Resume ID: {resume_id}'})


class ResumeCommentListCreateView(generics.ListCreateAPIView):
    """简历评论列表和创建"""
    permission_classes = [IsAuthenticated]
    
    def get(self, request, resume_id):
        return Response({'message': f'简历评论列表接口开发中 - Resume ID: {resume_id}'})


class ResumeCommentDetailView(generics.RetrieveUpdateDestroyAPIView):
    """简历评论详情"""
    permission_classes = [IsAuthenticated]
    
    def get(self, request, pk):
        return Response({'message': f'简历评论详情接口开发中 - ID: {pk}'})





@api_view(['POST'])
@permission_classes([IsAuthenticated])
def submit_resume(request, pk):
    """提交简历"""
    try:
        # 获取当前用户的学生对象
        student = get_student_for_user(request.user)
        if not student:
            return Response({'error': '当前用户不是学生'}, status=status.HTTP_403_FORBIDDEN)

        # 获取简历
        resume = get_object_or_404(Resume, id=pk, student=student)

        # 检查简历状态
        if resume.status in ['submitted', 'under_review', 'approved']:
            return Response({'error': '简历已提交或已审核，无法重复提交'}, status=status.HTTP_400_BAD_REQUEST)

        # 检查是否有文件
        if not (resume.generated_file or resume.uploaded_file):
            return Response({'error': '请先上传简历文件或生成简历'}, status=status.HTTP_400_BAD_REQUEST)

        # 更新简历状态
        resume.status = 'submitted'
        resume.save()

        return Response({
            'message': '简历提交成功',
            'status': resume.status
        })

    except Resume.DoesNotExist:
        return Response({'error': '简历不存在'}, status=status.HTTP_404_NOT_FOUND)
    except Exception as e:
        return Response({'error': str(e)}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


@api_view(['POST'])
@permission_classes([IsAuthenticated])
def submit_for_review(request, pk):
    """学生提交简历审核"""
    try:
        # 获取学生信息
        try:
            student = Student.objects.get(user=request.user)
        except Student.DoesNotExist:
            return Response({'error': '学生信息不存在'}, status=status.HTTP_403_FORBIDDEN)

        # 获取简历
        try:
            resume = Resume.objects.get(id=pk, student=student)
        except Resume.DoesNotExist:
            return Response({'error': '简历不存在或无权限访问'}, status=status.HTTP_404_NOT_FOUND)

        # 检查简历状态
        if resume.status in ['under_review', 'approved']:
            return Response({'error': '简历已提交审核或已通过，无法重复提交'}, status=status.HTTP_400_BAD_REQUEST)

        # 检查简历是否可以提交
        can_submit = False
        error_message = ''

        if resume.resume_type == 'uploaded':
            # 上传的简历，检查是否有文件
            if resume.uploaded_file:
                can_submit = True
            else:
                error_message = '请先上传简历文件'
        else:
            # 在线生成的简历，检查完成度
            completion_rate = float(resume.completion_rate or 0)
            if completion_rate >= 80:
                can_submit = True
            else:
                error_message = f'简历完成度不足80%（当前：{completion_rate}%），无法提交审核'

        if not can_submit:
            return Response({'error': error_message}, status=status.HTTP_400_BAD_REQUEST)

        # 更新简历状态
        resume.status = 'under_review'
        resume.save()

        # 更新学生的简历状态
        student.resume_status = 'submitted'
        student.save()

        return Response({
            'message': '简历已提交审核',
            'resume_id': resume.id,
            'status': resume.status
        })

    except Exception as e:
        return Response({'error': str(e)}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


@api_view(['POST'])
@permission_classes([IsAuthenticated])
def submit_for_ai_evaluation(request, pk):
    """学生提交简历AI评估（预留功能）"""
    try:
        # 获取学生信息
        try:
            student = Student.objects.get(user=request.user)
        except Student.DoesNotExist:
            return Response({'error': '学生信息不存在'}, status=status.HTTP_403_FORBIDDEN)

        # 获取简历
        try:
            resume = Resume.objects.get(id=pk, student=student)
        except Resume.DoesNotExist:
            return Response({'error': '简历不存在或无权限访问'}, status=status.HTTP_404_NOT_FOUND)

        # 检查简历是否可以评估
        can_evaluate = False
        error_message = ''

        if resume.resume_type == 'uploaded':
            if resume.uploaded_file:
                can_evaluate = True
            else:
                error_message = '请先上传简历文件'
        else:
            completion_rate = float(resume.completion_rate or 0)
            if completion_rate >= 60:
                can_evaluate = True
            else:
                error_message = f'简历完成度不足60%（当前：{completion_rate}%），无法进行AI评估'

        if not can_evaluate:
            return Response({'error': error_message}, status=status.HTTP_400_BAD_REQUEST)

        # TODO: 实现AI评估逻辑
        return Response({
            'message': 'AI评估功能正在开发中，敬请期待',
            'resume_id': resume.id,
            'feature_status': 'coming_soon'
        })

    except Exception as e:
        return Response({'error': str(e)}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


# 旧的review_resume函数已删除，使用新的review_resume_action函数


@api_view(['POST'])
@permission_classes([IsAuthenticated])
def submit_resume_for_review(request, resume_id):
    """学生提交简历审核"""
    try:
        resume = get_object_or_404(Resume, id=resume_id)

        # 检查权限：只有简历所属学生可以提交
        if request.user.role == 'student':
            student = get_student_for_user(request.user)
            if not student or resume.student != student:
                return Response({'error': '无权限操作此简历'}, status=status.HTTP_403_FORBIDDEN)
        elif request.user.role not in ['admin', 'teacher']:
            return Response({'error': '无权限操作'}, status=status.HTTP_403_FORBIDDEN)

        # 检查是否可以提交审核
        if not resume.can_submit_for_review():
            return Response({
                'error': '简历不满足提交条件',
                'details': f'当前状态：{resume.get_status_display()}，完成度：{resume.completion_rate}%'
            }, status=status.HTTP_400_BAD_REQUEST)

        # 提交审核
        submission_note = request.data.get('submission_note', '')
        version = resume.submit_for_review(request.user, submission_note)

        return Response({
            'message': '简历已提交审核',
            'resume_id': resume.id,
            'version_number': version.version_number,
            'status': resume.status,
            'submitted_at': version.submitted_at
        })

    except Exception as e:
        return Response({'error': str(e)}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


@api_view(['GET'])
@permission_classes([IsAuthenticated, IsTeacherOrAdmin])
def get_pending_reviews(request):
    """获取待审核的简历列表（老师端）"""
    try:
        user = request.user

        # 获取待审核的简历
        if user.role == 'teacher':
            # 老师只能看到分配给自己的学生的已提交审核的简历
            resumes = Resume.objects.filter(
                student__advisor=user,
                status__in=['pending_review', 'under_review', 'approved', 'rejected', 'needs_revision']
            ).select_related('student', 'template').order_by('-updated_at')
        else:
            # 管理员可以看到所有已提交审核的简历
            resumes = Resume.objects.filter(
                status__in=['pending_review', 'under_review', 'approved', 'rejected', 'needs_revision']
            ).select_related('student', 'template').order_by('-updated_at')

        # 如果有状态筛选，应用筛选，否则默认只显示待审核的
        status_filter = request.GET.get('status')
        if status_filter:
            resumes = resumes.filter(status=status_filter)
        else:
            # 默认只显示待审核的简历
            resumes = resumes.filter(status='pending_review')

        # 分页
        paginator = ResumePagination()
        page = paginator.paginate_queryset(resumes, request)

        # 序列化数据
        resume_data = []
        for resume in page:
            latest_submission = resume.submissions.first()
            resume_info = {
                'id': resume.id,
                'title': resume.title,
                'student_name': resume.student.name,
                'student_id': resume.student.student_id,
                'resume_type': resume.resume_type,  # 返回原始值而不是display值
                'status': resume.status,  # 添加状态字段
                'completion_rate': float(resume.completion_rate) if resume.completion_rate else 0,
                'submitted_at': latest_submission.submitted_at if latest_submission else None,
                'submission_note': latest_submission.submission_note if latest_submission else '',
                'file_url': resume.get_current_file().url if resume.get_current_file() else None,
                'created_at': resume.created_at,
                'updated_at': resume.updated_at,
                'review_date': resume.review_date,
                'review_comments': resume.review_comments
            }
            resume_data.append(resume_info)

        return paginator.get_paginated_response(resume_data)

    except Exception as e:
        return Response({'error': str(e)}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


@api_view(['GET'])
@permission_classes([IsAuthenticated, IsTeacherOrAdmin])
def get_teacher_resume_list(request):
    """获取老师可访问的简历列表（包括已审批的）"""
    try:
        user = request.user

        # 获取简历列表
        if user.role == 'teacher':
            # 老师只能看到分配给自己的学生的已提交审核的简历
            resumes = Resume.objects.filter(
                student__advisor=user,
                status__in=['pending_review', 'under_review', 'approved', 'rejected', 'needs_revision']
            ).select_related('student', 'template').order_by('-updated_at')
        else:
            # 管理员可以看到所有已提交审核的简历
            resumes = Resume.objects.filter(
                status__in=['pending_review', 'under_review', 'approved', 'rejected', 'needs_revision']
            ).select_related('student', 'template').order_by('-updated_at')

        # 筛选条件
        status_filter = request.GET.get('status')
        if status_filter:
            resumes = resumes.filter(status=status_filter)

        # 是否只显示已审批的简历
        reviewed_only = request.GET.get('reviewed')
        if reviewed_only == 'true':
            resumes = resumes.filter(status__in=['approved', 'rejected', 'needs_revision'])
            # 在已审批简历页面，老师只能看到自己审批的简历
            if user.role == 'teacher':
                resumes = resumes.filter(reviewer=user)

        # 日期范围筛选
        start_date = request.GET.get('start_date')
        end_date = request.GET.get('end_date')
        if start_date:
            resumes = resumes.filter(review_date__gte=start_date)
        if end_date:
            resumes = resumes.filter(review_date__lte=end_date)

        # 搜索
        search = request.GET.get('search')
        if search:
            resumes = resumes.filter(
                Q(title__icontains=search) |
                Q(student__name__icontains=search)
            )

        # 分页
        paginator = ResumePagination()
        page = paginator.paginate_queryset(resumes, request)

        # 序列化数据
        resume_data = []
        for resume in page:
            resume_info = {
                'id': resume.id,
                'title': resume.title,
                'student_name': resume.student.name,
                'student_id': resume.student.student_id,
                'resume_type': resume.resume_type,
                'status': resume.status,
                'completion_rate': float(resume.completion_rate) if resume.completion_rate else 0,
                'created_at': resume.created_at,
                'updated_at': resume.updated_at,
                'reviewed_at': resume.review_date,
                'reviewer_name': resume.reviewer.username if resume.reviewer else '',
                'review_comments': resume.review_comments or '',
                'file_url': resume.get_current_file().url if resume.get_current_file() else None,
            }
            resume_data.append(resume_info)

        return paginator.get_paginated_response(resume_data)

    except Exception as e:
        return Response({'error': str(e)}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


@api_view(['POST'])
@permission_classes([IsAuthenticated, IsTeacherOrAdmin])
def review_resume_action(request, resume_id):
    """审核简历"""
    try:
        resume = get_object_or_404(Resume, id=resume_id)
        user = request.user

        # 检查权限：老师只能审核分配给自己的学生的简历
        if user.role == 'teacher' and resume.student.advisor != user:
            return Response({'error': '无权限审核此简历'}, status=status.HTTP_403_FORBIDDEN)

        # 检查简历状态
        if resume.status != 'pending_review':
            return Response({'error': '简历当前状态不允许审核'}, status=status.HTTP_400_BAD_REQUEST)

        # 获取审核数据
        review_status = request.data.get('review_status')
        review_comments = request.data.get('review_comments', '')

        if review_status not in ['approved', 'rejected', 'needs_revision']:
            return Response({'error': '无效的审核结果'}, status=status.HTTP_400_BAD_REQUEST)

        # 设置默认审核建议
        if not review_comments:
            default_comments = {
                'approved': '简历审核通过，请准备申请模拟面试',
                'rejected': '简历严重不合格，请重新编写',
                'needs_revision': '请根据审核建议修改简历'
            }
            review_comments = default_comments.get(review_status, '')

        # 创建审核记录
        from .models import ResumeReview
        review = ResumeReview.objects.create(
            resume=resume,
            reviewer=user,
            review_status=review_status,
            review_comments=review_comments
        )

        # 复制当前文件到审核记录
        current_file = resume.get_current_file()
        if current_file:
            review.reviewed_file = current_file
            review.reviewed_file_name = current_file.name
            review.save()

        # 更新简历状态
        status_mapping = {
            'approved': 'approved',
            'rejected': 'rejected',
            'needs_revision': 'needs_revision'
        }
        resume.status = status_mapping[review_status]
        resume.reviewer = user
        resume.review_date = review.review_date
        resume.review_comments = review_comments
        resume.save()

        # 关联最新版本到审核记录
        latest_version = resume.get_latest_version()
        if latest_version:
            latest_version.review = review
            latest_version.save()

        return Response({
            'message': f'简历审核完成：{review.get_review_status_display()}',
            'resume_id': resume.id,
            'review_id': review.id,
            'status': resume.status,
            'review_status': review_status,
            'review_comments': review_comments,
            'reviewer': user.username,
            'review_date': review.review_date
        })

    except Exception as e:
        return Response({'error': str(e)}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


@api_view(['GET'])
@permission_classes([IsAuthenticated])
def get_resume_versions(request, resume_id):
    """获取简历历史版本"""
    try:
        resume = get_object_or_404(Resume, id=resume_id)
        user = request.user

        # 检查权限
        if user.role == 'student':
            student = get_student_for_user(user)
            if not student or resume.student != student:
                return Response({'error': '无权限查看此简历'}, status=status.HTTP_403_FORBIDDEN)
        elif user.role == 'teacher':
            if resume.student.advisor != user:
                return Response({'error': '无权限查看此简历'}, status=status.HTTP_403_FORBIDDEN)
        elif user.role not in ['admin']:
            return Response({'error': '无权限操作'}, status=status.HTTP_403_FORBIDDEN)

        # 获取版本列表
        versions = resume.versions.select_related('review', 'review__reviewer').order_by('-version_number')

        version_data = []
        for version in versions:
            version_info = {
                'id': version.id,
                'version_number': version.version_number,
                'title': version.title,
                'status': version.status,
                'status_display': version.get_status_display(),
                'completion_rate': version.completion_rate,
                'submitted_at': version.submitted_at,
                'submission_note': version.submission_note,
                'file_url': version.file_path.url if version.file_path else None,
                'file_name': version.file_name,
                'file_type': version.file_type,
                'file_size': version.file_size,
                'created_at': version.created_at,
                'review': None
            }

            # 添加审核信息
            if version.review:
                version_info['review'] = {
                    'id': version.review.id,
                    'review_status': version.review.review_status,
                    'review_status_display': version.review.get_review_status_display(),
                    'review_comments': version.review.review_comments,
                    'reviewer_name': version.review.reviewer.username,
                    'review_date': version.review.review_date
                }

            version_data.append(version_info)

        return Response({
            'resume_id': resume.id,
            'resume_title': resume.title,
            'student_name': resume.student.name,
            'versions': version_data,
            'total_versions': len(version_data)
        })

    except Exception as e:
        return Response({'error': str(e)}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


@api_view(['GET'])
@permission_classes([IsAuthenticated])
def get_student_resume_history(request, student_id):
    """获取学生的简历历史记录（老师端）"""
    try:
        user = request.user
        student = get_object_or_404(Student, id=student_id)

        # 检查权限：老师只能查看分配给自己的学生
        if user.role == 'teacher' and student.advisor != user:
            return Response({'error': '无权限查看此学生信息'}, status=status.HTTP_403_FORBIDDEN)
        elif user.role not in ['admin', 'teacher']:
            return Response({'error': '无权限操作'}, status=status.HTTP_403_FORBIDDEN)

        # 获取学生的所有简历
        resumes = Resume.objects.filter(student=student).order_by('-created_at')

        resume_data = []
        for resume in resumes:
            # 获取简历的版本和审核记录
            versions = resume.versions.select_related('review', 'review__reviewer').order_by('-version_number')
            submissions = resume.submissions.select_related('submitted_by').order_by('-submitted_at')

            version_list = []
            for version in versions:
                version_info = {
                    'version_number': version.version_number,
                    'title': version.title,
                    'status': version.get_status_display(),
                    'submitted_at': version.submitted_at,
                    'submission_note': version.submission_note,
                    'file_url': version.file_path.url if version.file_path else None,
                    'file_name': version.file_name,
                    'review': None
                }

                if version.review:
                    version_info['review'] = {
                        'review_status': version.review.get_review_status_display(),
                        'review_comments': version.review.review_comments,
                        'reviewer_name': version.review.reviewer.username,
                        'review_date': version.review.review_date
                    }

                version_list.append(version_info)

            resume_info = {
                'id': resume.id,
                'title': resume.title,
                'resume_type': resume.get_resume_type_display(),
                'current_status': resume.get_status_display(),
                'completion_rate': resume.completion_rate,
                'created_at': resume.created_at,
                'updated_at': resume.updated_at,
                'versions': version_list,
                'total_submissions': submissions.count()
            }

            resume_data.append(resume_info)

        return Response({
            'student_id': student.id,
            'student_name': student.name,
            'student_number': student.student_id,
            'resumes': resume_data,
            'total_resumes': len(resume_data)
        })

    except Exception as e:
        return Response({'error': str(e)}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


@api_view(['GET'])
@permission_classes([IsAuthenticated, IsAdminUser])
def get_all_resumes(request):
    """管理员获取所有简历列表"""
    try:
        # 获取查询参数
        status_filter = request.GET.get('status')
        student_name = request.GET.get('student_name')
        resume_type = request.GET.get('resume_type')
        advisor_id = request.GET.get('advisor_id')

        # 构建查询
        resumes = Resume.objects.all().select_related('student', 'template', 'student__advisor').order_by('-updated_at')

        # 应用筛选
        if status_filter:
            resumes = resumes.filter(status=status_filter)
        if student_name:
            resumes = resumes.filter(student__name__icontains=student_name)
        if resume_type:
            resumes = resumes.filter(resume_type=resume_type)
        if advisor_id:
            resumes = resumes.filter(student__advisor_id=advisor_id)

        # 分页
        paginator = ResumePagination()
        page = paginator.paginate_queryset(resumes, request)

        # 序列化数据
        resume_data = []
        for resume in page:
            latest_submission = resume.submissions.first()
            latest_review = resume.reviews.first()

            resume_info = {
                'id': resume.id,
                'title': resume.title,
                'student_name': resume.student.name,
                'student_id': resume.student.student_id,
                'advisor_name': resume.student.advisor.username if resume.student.advisor else '未分配',
                'resume_type': resume.resume_type,
                'status': resume.status,
                'completion_rate': float(resume.completion_rate) if resume.completion_rate else 0,
                'created_at': resume.created_at,
                'updated_at': resume.updated_at,
                'submitted_at': latest_submission.submitted_at if latest_submission else None,
                'review_date': latest_review.review_date if latest_review else None,
                'reviewer': latest_review.reviewer.username if latest_review else None,
                'file_url': resume.get_current_file().url if resume.get_current_file() else None
            }
            resume_data.append(resume_info)

        return paginator.get_paginated_response(resume_data)

    except Exception as e:
        return Response({'error': str(e)}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


@api_view(['GET'])
@permission_classes([IsAuthenticated, IsAdminUser])
def get_review_statistics(request):
    """获取审核统计信息"""
    try:
        from django.db.models import Count, Q
        from datetime import datetime, timedelta

        # 基础统计
        total_resumes = Resume.objects.count()
        pending_reviews = Resume.objects.filter(status='pending_review').count()
        approved_resumes = Resume.objects.filter(status='approved').count()
        rejected_resumes = Resume.objects.filter(status='rejected').count()
        needs_revision = Resume.objects.filter(status='needs_revision').count()

        # 按类型统计
        type_stats = Resume.objects.values('resume_type').annotate(count=Count('id'))

        # 按老师统计审核数量
        teacher_stats = Resume.objects.filter(
            student__advisor__isnull=False
        ).values(
            'student__advisor__username'
        ).annotate(
            total=Count('id'),
            pending=Count('id', filter=Q(status='pending_review')),
            approved=Count('id', filter=Q(status='approved')),
            rejected=Count('id', filter=Q(status__in=['rejected', 'needs_revision']))
        ).order_by('-total')

        # 最近7天的提交统计
        seven_days_ago = datetime.now() - timedelta(days=7)
        recent_submissions = Resume.objects.filter(
            submissions__submitted_at__gte=seven_days_ago
        ).values('submissions__submitted_at__date').annotate(count=Count('id')).order_by('submissions__submitted_at__date')

        return Response({
            'total_resumes': total_resumes,
            'pending_reviews': pending_reviews,
            'approved_resumes': approved_resumes,
            'rejected_resumes': rejected_resumes,
            'needs_revision': needs_revision,
            'type_statistics': list(type_stats),
            'teacher_statistics': list(teacher_stats),
            'recent_submissions': list(recent_submissions)
        })

    except Exception as e:
        return Response({'error': str(e)}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


@api_view(['POST'])
@permission_classes([IsAuthenticated, IsAdminUser])
def update_resume_status(request):
    """管理员批量更新简历状态"""
    try:
        resume_ids = request.data.get('resume_ids', [])
        new_status = request.data.get('status')
        comments = request.data.get('comments', '')

        if not resume_ids or not new_status:
            return Response({'error': '缺少必要参数'}, status=status.HTTP_400_BAD_REQUEST)

        if new_status not in ['pending_review', 'approved', 'rejected', 'needs_revision']:
            return Response({'error': '无效的状态值'}, status=status.HTTP_400_BAD_REQUEST)

        # 批量更新
        updated_count = Resume.objects.filter(id__in=resume_ids).update(
            status=new_status,
            reviewer=request.user,
            review_date=timezone.now(),
            review_comments=comments
        )

        return Response({
            'message': f'成功更新 {updated_count} 个简历的状态',
            'updated_count': updated_count,
            'new_status': new_status
        })

    except Exception as e:
        return Response({'error': str(e)}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)





class ResumeTemplateViewSet(viewsets.ReadOnlyModelViewSet):
    """简历模板视图集"""

    queryset = ResumeTemplate.objects.filter(is_active=True)
    serializer_class = ResumeTemplateSerializer
    permission_classes = [IsAuthenticated]

    def list(self, request, *args, **kwargs):
        """获取模板列表"""
        queryset = self.get_queryset()
        serializer = self.get_serializer(queryset, many=True)
        return Response({
            'results': serializer.data,
            'count': len(serializer.data)
        })


@api_view(['POST'])
@permission_classes([IsAuthenticated])
def generate_resume_with_template(request):
    """使用模板生成简历"""
    from .serializers import ResumeGenerationRequestSerializer, ResumeGenerationRecordSerializer
    from .resume_generator import ResumeGenerator
    from django.utils import timezone
    import uuid

    # 验证请求数据
    serializer = ResumeGenerationRequestSerializer(data=request.data)
    if not serializer.is_valid():
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

    data = serializer.validated_data

    try:
        # 获取学生信息
        student = get_student_for_user(request.user)
        if not student:
            return Response({'error': '学生信息不存在'}, status=status.HTTP_400_BAD_REQUEST)

        # 获取模板
        template = ResumeTemplate.objects.get(id=data['template_id'])

        # 创建生成记录
        generation_record = ResumeGenerationRecord.objects.create(
            student=student,
            template=template,
            title=data['title'],
            format=data['format'],
            form_data=data,
            status='processing',
            started_at=timezone.now()
        )

        # 处理头像文件
        avatar_path = None
        if 'avatar' in request.FILES:
            avatar_file = request.FILES['avatar']
            # 保存头像文件
            avatar_filename = f"avatar_{student.id}_{uuid.uuid4().hex[:8]}.{avatar_file.name.split('.')[-1]}"
            avatar_dir = os.path.join(settings.MEDIA_ROOT, 'avatars')
            os.makedirs(avatar_dir, exist_ok=True)
            avatar_path = os.path.join(avatar_dir, avatar_filename)

            with open(avatar_path, 'wb+') as destination:
                for chunk in avatar_file.chunks():
                    destination.write(chunk)

        # 准备简历数据
        resume_data = {
            'title': data['title'],
            'basic_info': {
                '姓名': data['name'],
                '手机': data['phone'],
                '邮箱': data['email'],
                '学校': data.get('school', ''),
                '专业': data.get('major', ''),
            },
            'self_introduction': data.get('introduction', ''),
            'avatar_path': avatar_path,
            'education': [],
            'work_experience': [],
            'projects': [],
            'skills': [],
            'awards': []
        }

        # 生成简历
        generator = ResumeGenerator(resume_data, template.style_name)

        if data['format'] == 'pdf':
            doc = generator.generate_pdf()
            file_extension = 'pdf'
            content_type = 'application/pdf'
        else:
            doc = generator.generate_word()
            file_extension = 'docx'
            content_type = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'

        # 保存文件
        filename = f"{data['title']}_{uuid.uuid4().hex[:8]}.{file_extension}"
        file_path = os.path.join('generated_resumes', filename)

        # 确保目录存在
        os.makedirs(os.path.dirname(os.path.join(settings.MEDIA_ROOT, file_path)), exist_ok=True)

        # 保存文档
        full_path = os.path.join(settings.MEDIA_ROOT, file_path)
        if data['format'] == 'pdf':
            with open(full_path, 'wb') as f:
                f.write(doc)
        else:
            doc.save(full_path)

        # 更新生成记录
        generation_record.generated_file = file_path
        generation_record.status = 'completed'
        generation_record.completed_at = timezone.now()
        generation_record.save()

        # 增加模板使用次数
        template.increment_usage()

        # 创建简历记录
        resume = Resume.objects.create(
            student=student,
            title=data['title'],
            resume_type='generated',
            generated_file=file_path,
            generated_file_name=filename,
            generated_file_type=file_extension,
            status='draft'
        )

        return Response({
            'message': '简历生成成功',
            'resume_id': resume.id,
            'generation_record_id': generation_record.id,
            'file_url': f"/api/resume-management/resumes/{resume.id}/file/",
            'download_url': f"/api/resume-management/resumes/{resume.id}/download/"
        })

    except ResumeTemplate.DoesNotExist:
        return Response({'error': '模板不存在'}, status=status.HTTP_404_NOT_FOUND)
    except Exception as e:
        # 更新生成记录为失败状态
        if 'generation_record' in locals():
            generation_record.status = 'failed'
            generation_record.error_message = str(e)
            generation_record.completed_at = timezone.now()
            generation_record.save()

        return Response({'error': f'生成失败: {str(e)}'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
